<template>
  <ManageLayout>
    <template #header-left>
      <h3>文章列表</h3>
    </template>
    <template #header-right>
      <div>
        <n-input v-model:value="keyword" @keydown.enter.stop="handleSearch">
          <template #prefix>
            <TextIcon icon="mdi:search"></TextIcon>
          </template>
        </n-input>
      </div>
    </template>
    <div class="h-full flex flex-col ">
      <CurdTable ref="tableRef"
                 :columns="columns"
                 :and-params="andParams"
                 :or-params="orParams"
                 :order-params="orderParams"
                 :get-data="api.post.queryList"></CurdTable>
    </div>
  </ManageLayout>
  <PostPreviewModal ref="previewRef"></PostPreviewModal>
</template>

<script setup lang="ts">

import ManageLayout from "@/view/pc/manage/components/ManageLayout.vue";
import CurdTable from "@/components/pc/table/CurdTable.vue";
import {h, nextTick, onMounted, ref} from "vue";
import api from "@/api";
import ArrayTag from "@/components/pc/tag/ArrayTag.vue";
import {renderIconH} from "@/utils";
import dayjs from "@/utils/dayjs";
import {NButton} from "naive-ui";
import router from "@/router";
import TextIcon from "@/components/pc/icon/TextIcon.vue";
import PostPreviewModal from "@/components/pc/modal/PostPreviewModal.vue";
import {useAdminStore} from "@/store/module/admin";

const adminStore = useAdminStore()
const tableRef = ref()
const previewRef = ref()
onMounted(() => {
  handleSearch()
})
const columnsSort = ref({
  visibility: false,
  createdAt: false,
  updatedAt: 'descend',
})
const columns = ref([
  {title: 'ID', key: 'id', width: 2, ellipsis: {tooltip: true}, align: 'center',},
  {title: '标题', key: 'title', width: 5, ellipsis: {tooltip: true}, align: 'center',},
  {
    title: '类名', key: 'categoryName', width: 3, ellipsis: {tooltip: true}, align: 'center',
  },
  {
    title: '标签', key: 'tags', width: 5, ellipsis: {tooltip: true}, align: 'center',
    render(row: any) {
      return row.tags ? h(ArrayTag, {tags: row.tags ? JSON.parse(row.tags) : []}) : '-'
    }
  },
  {
    title: '权限',
    key: 'visibility',
    width: 3,
    ellipsis: {tooltip: true},
    align: 'center',
    sorter: {
      multiple: 1,
    },
    render(row: any) {
      return h('div', {class: row.visibility === 'private' ? 'text-red-600' : 'text-blue-600'}, row.visibility)
    },
    renderSorterIcon: (options: any) => {
      if (!options.order) {
        andParams.value.visibility = ''
      } else if (options.order === 'ascend') {
        andParams.value.visibility = 'public'
      } else if (options.order === 'descend') {
        andParams.value.visibility = 'private'
      }
      if (options.order != columnsSort.value.visibility) {
        handleSearch()
        columnsSort.value.visibility = options.order
      }
      if (!options.order) {
        return renderIconH('mdi:lock')
      } else if (options.order === 'descend') {
        return renderIconH('mdi:lock')
      } else {
        return renderIconH('clarity:unlock-solid')
      }
    },
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: 5,
    ellipsis: {tooltip: true},
    align: 'center',
    sorter: {
      multiple: 1,
    },
    render(row: any) {
      return [h('div', {}, dayjs(row.createdAt).format('YYYY-MM-DD HH:mm')),
        h('div', {class: 'text-gray-400'}, dayjs(row.createdAt).fromNow())]
    },
    renderSorterIcon: (options: any) => {
      if (!options.order) {
        orderParams.value.createdAt = ''
      } else if (options.order === 'ascend') {
        orderParams.value.createdAt = '升序'
      } else if (options.order === 'descend') {
        orderParams.value.createdAt = '降序'
      }
      if (options.order != columnsSort.value.createdAt) {
        handleSearch()
        columnsSort.value.createdAt = options.order
      }
      if (!options.order || options.order === 'descend') {

        return renderIconH('ph:sort-ascending')
      } else {
        return renderIconH('ph:sort-descending')
      }
    },
  },
  {
    title: '更新时间',
    key: 'updatedAt',
    width: 5,
    ellipsis: {tooltip: true},
    align: 'center',
    sorter: {
      multiple: 1,
    },
    defaultSortOrder: columnsSort.value.updatedAt,
    renderSorterIcon: (options: any) => {
      if (!options.order) {
        orderParams.value.updatedAt = ''
      } else if (options.order === 'ascend') {
        orderParams.value.updatedAt = '升序'
      } else if (options.order === 'descend') {
        orderParams.value.updatedAt = '降序'
      }
      if (options.order != columnsSort.value.updatedAt) {
        handleSearch()
        columnsSort.value.updatedAt = options.order
      }
      if (!options.order || options.order === 'descend') {
        return renderIconH('ph:sort-ascending')
      } else {
        return renderIconH('ph:sort-descending')
      }
    },
    render(row: any) {
      return [h('div', {}, dayjs(row.updatedAt).format('M-D HH:mm')),
        h('div', {class: 'text-gray-400'}, dayjs(row.updatedAt).fromNow())]
    }
  },
  {
    title: '操作', key: 'actions', width: 8, align: 'center',
    render(row: any) {
      return [
        h(NButton, {
          round: true,
          secondary: true,
          size: 'tiny',
          type: "success",
          onClick: () => handlePreview(row)
        }, {default: () => "预览"}),
        h(NButton, {
          round: true,
          secondary: true,
          size: 'tiny',
          type: "info",
          onClick: () => handleEdit(row)
        }, {default: () => "编辑"}),
        h(NButton, {
          round: true,
          secondary: true,
          size: 'tiny',
          type: "error",
          onClick: () => handleRemove(row)
        }, {default: () => "删除"}),
      ]
    }
  }
])
const andParams = ref({
  visibility: '',
})
const orParams = ref({})
const orderParams = ref({
  createdAt: '',
  updatedAt: '',
})
const keyword = ref('')

const handleSearch = () => {
  const searchValue = `%${keyword.value}%`;
  orParams.value = {
    id: searchValue,
    title: searchValue,
    username: searchValue,
    categoryName: searchValue,
    tags: searchValue
  }
  nextTick(() => {
    tableRef.value.doQuery()
  })
}
const handleRemove = (row: any) => {
  console.log(row)
  window.$dialog.warning({
    title: '提醒',
    content: '确定删除该文章？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      api.post.remove({id: row.id}).then(res => {
        if (res.data.code === 0) {
          window.$message.success('删除成功')
          handleSearch()
        }
      })
    }
  })

}
const handlePreview = (row: any) => {
  let tmp = JSON.parse(JSON.stringify(row))
  tmp.tags = tmp ? JSON.parse(tmp.tags) : []
  console.log('row',tmp)
  previewRef.value.doParamsShow({
    post: tmp
  })
  adminStore.openPost(tmp, '预览')

}
const handleEdit = (row: any) => {
  let r = router.resolve({
    path: '/pc/manage/edit',
    query: {
      id: row.id
    }
  })
  window.open(r.href, '_blank');
  adminStore.openPost(row, '编辑')
}
</script>

<style scoped>

</style>